package com.example.tonyzxb.autoemulator;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.autonavi.amapauto.ClientService;
import com.example.tonyzxb.autoemulator.common.AmapIntent;
import com.example.tonyzxb.autoemulator.model.IntentBean;
import com.example.tonyzxb.autoemulator.receive.AmapReceiver;
import com.google.gson.Gson;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Callable;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

 /**
  *车机模拟器 数据放在SD卡 /amapcar 里面 
  * @author tony.zxb@alibaba-inc.com
  * @since  2016/1/20 16:14
  */
public class MainFragment extends Fragment implements View.OnClickListener {

    @Bind(R.id.btn_float)
    Button btnFloat;
    @Bind(R.id.btn_manual)
    Button btnManual;
//    @Bind(R.id.button3)
//    Button btnTtsStreamType;
    @Bind(R.id.listView)
    ListView lvMsg;
    @Bind(R.id.tv_clear)
    TextView tvClear;
    @Bind(R.id.et_input)
    EditText etInput;
    @Bind(R.id.btn_history)
    Button btnHistory;
    @Bind(R.id.lv_intent)
    ListView lvIntent;
     @Bind(R.id.rg_config)
     RadioGroup rgConfig;

     


    private Activity mActivity;
    private ArrayList<String> msgList = new ArrayList<String>();
    private MsgAdapter msgAdapter;
    private ArrayList<IntentBean.SendEntity> sendList = new ArrayList<IntentBean.SendEntity>();
    private SendAdapter sendAdapter;
     private ArrayList<IntentBean> intentList = new ArrayList<IntentBean>();
     private IntentAdapter intentAdapter;


    public static final String JSON_FILE = "changan.json";
    public static final String CONFIG_FOLDER="amapcar";
    //上一次Intent
    private Intent lastIntent;

     public static MainFragment newInstance() {
        Bundle args = new Bundle();
        MainFragment fragment = new MainFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // return super.onCreateView(inflater, container, savedInstanceState);
        View view = View.inflate(getActivity(), R.layout.main_fg, null);
        ButterKnife.bind(this, view);

        mActivity = this.getActivity();
//        btnCarLamp.setOnClickListener(this);
        btnFloat.setOnClickListener(this);
        btnManual.setOnClickListener(this);
        tvClear.setOnClickListener(this);
        btnHistory.setOnClickListener(this);

        msgAdapter = new MsgAdapter();
        lvMsg.setAdapter(msgAdapter);
        lvMsg.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);

//读取 Asset 保留代码
//        makeObservable(readAsset())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Action1<IntentBean>() {
//                    @Override
//                    public void call(IntentBean bean) {
////                Log.e("success", "Action1 func call sucess:  "+list.size()+"");
//                        if (bean != null) {
//                            sendList.addAll(bean.send);
//                            sendAdapter = new SendAdapter();
//                            lvIntent.setAdapter(sendAdapter);
//
//                            AmapReceiver amapReceiver = new AmapReceiver();
//                            IntentFilter intentFilter = new IntentFilter();
//                            for (IntentBean.ReceiverEntity receiver :
//                                    bean.receiver) {
//                                //动态广播的Receiver
//                                // TODO: 2016/1/20 Filter 能否添加多个 
//                                intentFilter.addAction(receiver.action);
//                            }
//                            mActivity.registerReceiver(amapReceiver, intentFilter);
//                        }
//                    }
//                }, new Action1<Throwable>() {
//                    @Override
//                    public void call(Throwable throwable) {
//                        Log.e("error", "Action1 func call Error ", throwable);
//                    }
//                });

        makeObservable(readSdCard())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<IntentBean>>() {
                    @Override
                    public void call(List<IntentBean> list) {
                        intentList.addAll(list);
                        for (IntentBean bean : list) {
                            RadioButton radio = new RadioButton(mActivity);
                            radio.setText(bean.name);
                            rgConfig.addView(radio);
                        }
                    }
                });
                

        return view;
    }

    /**
     * 读取配置文件 Rxjava方式
     *
     * @return
     */
    private Callable<IntentBean> readAsset() {
        return new Callable<IntentBean>() {

            @Override
            public IntentBean call() throws Exception {
                AssetManager assetManager = mActivity.getAssets();
                InputStream in = assetManager.open(JSON_FILE);
                Gson gson = new Gson();
                return gson.fromJson(new InputStreamReader(in), IntentBean.class);
//                Type typeOfT = new TypeToken<List<IntentBean>>(){}.getType();
//                List<IntentBean> sendList = gson.fromJson(new InputStreamReader(in), typeOfT);
//                return sendList;
            }
        };
    }

     // TODO: 2016/1/20 使用 RXjava实现 
    private Callable<List<IntentBean>> readSdCard() {
        return new Callable<List<IntentBean>>(){

            @Override
            public List<IntentBean> call() throws Exception {
                List<IntentBean> beanList=new ArrayList<IntentBean>();
                File root = new File(Environment.getExternalStorageDirectory()+"/"+CONFIG_FOLDER);
                File[] files = root.listFiles();
                for (File file : files) {
                    FileInputStream inputStream = new FileInputStream(file);
                    Gson gson = new Gson();
                    IntentBean bean =gson.fromJson(new InputStreamReader(inputStream),IntentBean.class);
                    bean.name=file.getName();
                    beanList.add(bean);
                }
                return beanList;

            }
        };
    }
    
    
    

    private static <T> Observable<T> makeObservable(final Callable<T> func) {
        return Observable.create(
                new Observable.OnSubscribe<T>() {
                    @Override
                    public void call(Subscriber<? super T> subscriber) {
                        try {
                            subscriber.onNext(func.call());
                        } catch (Exception ex) {
                            subscriber.onError(ex);
                            Log.e("error", "Error func call ", ex);
                        }
                    }
                }).subscribeOn(Schedulers.io());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public static void start(Context context) {
        Intent starter = new Intent(context, MainFragment.class);
        // starter.putExtra();
        context.startActivity(starter);
    }

    /**
     * 往intent里面加入参数
     *
     * @param intent 传入的Intent
     * @param data   car_mode=0,test=true （多参数以,隔开）
     */
    public static void putExtra(Intent intent, String data) {

        String[] split = data.split(",");
        for (String str : split) {
            String[] pair = str.split("=");
            if (pair.length == 2) {
                intent.putExtra(pair[0], pair[1]);
            }
        }

    }

    public static String createMsg(Intent intent) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.CHINA);
        StringBuffer msg = new StringBuffer(sdf.format(new Date()));
        msg.append("\n sendBroadcast intent: " + intent);
        msg.append("\n extra: " + intent.getExtras().toString());
        return msg.toString();
    }

    @Override
    public void onClick(View v) {
        String data = etInput.getText().toString();
        Intent intent = new Intent();
        putExtra(intent, data);

        switch (v.getId()) {
            case R.id.btn_manual:
                intent.setAction(AmapIntent.ACTION_DIMER);
                sendIntent(intent);
                break;
            case R.id.btn_float:
                int checkOrder=0;
                int checkedRadioButtonId = rgConfig.getCheckedRadioButtonId();
                for (int i = 0; i < rgConfig.getChildCount(); i++) {
                    if(rgConfig.getChildAt(i).getId()==checkedRadioButtonId){
                        checkOrder=i;
                        break;
                    }
                }
                IntentBean bean = intentList.get(checkOrder);

                //动态注册：
                AmapReceiver amapReceiver = new AmapReceiver();
                IntentFilter intentFilter = new IntentFilter();
                for (IntentBean.ReceiverEntity receiver : bean.receiver) {
                    // 动态广播的Receiver
                    intentFilter.addAction(receiver.action);
                }
                mActivity.registerReceiver(amapReceiver, intentFilter);
                
                //启动FxService
                intent = new Intent(mActivity, ClientService.class);
                sendList.clear();
                sendList.addAll(bean.send);
                intent.putExtra(Intent.EXTRA_TEXT, sendList);
                mActivity.startService(intent);
                
                break;
            case R.id.tv_clear:
                msgList.clear();
                msgAdapter.notifyDataSetChanged();
                break;
            case R.id.btn_history:
                if (lastIntent != null) {
                    sendIntent(lastIntent);
                } else {
                    Toast.makeText(mActivity, "上次请求为空", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    public void sendIntent(Intent intent) {
        //发送广播
        mActivity.sendBroadcast(intent);
        //更新Log
        msgList.add(createMsg(intent));
        msgAdapter.notifyDataSetChanged();

        lastIntent = intent;
    }

    class MsgAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return msgList.size();
        }

        @Override
        public Object getItem(int position) {
            return msgList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(mActivity, R.layout.main_fg_item, null);
            }

            String msg = msgList.get(position);
            ((TextView) convertView).setText(msg);
            return convertView;
        }
    }


    class SendAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return sendList.size();
        }

        @Override
        public Object getItem(int position) {
            return sendList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(mActivity, R.layout.item_main_fragment_intent, null);
            }

            final IntentBean.SendEntity bean = sendList.get(position);
            ((Button) convertView).setText(bean.name);
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setAction(bean.action);
                    putExtra(intent, bean.extra);
                    sendIntent(intent);
                }
            });
            return convertView;
        }
    }


     class IntentAdapter extends BaseAdapter {

         @Override
         public int getCount() {
             return intentList.size();
         }

         @Override
         public Object getItem(int position) {
             return intentList.get(position);
         }

         @Override
         public long getItemId(int position) {
             return position;
         }

         @Override
         public View getView(int position, View convertView, ViewGroup parent) {
             if (convertView == null) {
                 convertView = View.inflate(mActivity, R.layout.item_main_fragment_intent, null);
             }

             final IntentBean  bean = intentList.get(position);
             ((Button) convertView).setText(bean.name);
            
             return convertView;
         }
     }
}
